package com.xfg.search.controller;

import com.xfg.search.entity.Oil;
import com.xfg.search.entity.User;
import com.xfg.search.service.AdminService;
import com.xfg.search.service.UserService;
import com.xfg.search.serviceImpl.CreateTokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("admin")
@Slf4j
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Resource
    private CreateTokenService createTokenService;
    //    全文检索
    @PostMapping("login")
    public Map<String,Object> search( @RequestBody User user) throws IOException {
        String username= user.getUsername();
        String password=user.getPassword();
        log.info(username+password);
        HashMap<String,Object> map=new HashMap<>();
        User ruser=adminService.login(username,password);
        if (ruser==null){
        map.put("msg","密码错误或账号不存在");
        map.put("statue",0);
            System.out.println("222");
        }else {
            String token=createTokenService.createToken(ruser);
            map.put("token",token);
            map.put("user",ruser);
            map.put("msg","登录成功");
            map.put("statue",1);
        }
        return map;
    }
    @PostMapping("/upload")
    public Map<String,String> upload(@RequestParam("file") MultipartFile excelFile,Integer id) throws Exception{
        Map<String,String> map = new HashMap<>();
        if (excelFile.isEmpty()){
            map.put("mag","文件夹为空，重新上传");
            return map;
        }else {
            String fileName = excelFile.getOriginalFilename();
            InputStream is = excelFile.getInputStream();
            if(adminService.importInfo(fileName,is,id)){
                map.put("msg","数据添加成功");
                return map;
            }else {
                map.put("msg","数据添加失败，请重新添加");
                return map;
            }
        }
    }

}
